import { AppDispatch } from '@/store/index';
import {
  getUserInfoAPI,
  getUserProfileAPI,
  updatePhotoAPI,
  updateProfileAPI,
} from '@/api/user';
import { getCodeAPI, getTokenAPI, LoginFormType } from '@/api/login';
import { setAuth } from '@/utils/storage';
import { ProfileType } from '../reducers/user';

export const sendCodesAction = (mobile: string) => {
  return async (dispatch: AppDispatch) => {
    const res = await getCodeAPI(mobile);
    console.log(res);
  };
};

export const loginAction = (data: LoginFormType) => {
  return async (dispatch: AppDispatch) => {
    const res = await getTokenAPI(data);
    // 保存到 redux
    dispatch({ type: 'user/saveAuth', payload: res.data });
    // 保存到 本地存储
    setAuth(res.data);
  };
};

export const getUserInfoAction = () => {
  return async (dispatch: AppDispatch) => {
    const res = await getUserInfoAPI();
    dispatch({
      type: 'user/saveUserInfo',
      payload: res.data,
    });
  };
};

export const getUserProfileAction = () => {
  return async (dispatch: AppDispatch) => {
    const res = await getUserProfileAPI();
    dispatch({
      type: 'user/saveProfile',
      payload: res.data,
    });
  };
};

export const updatePhotoAction = (data: FormData) => {
  return async (dispatch: AppDispatch) => {
    const res = await updatePhotoAPI(data);
    dispatch({
      type: 'user/updateProfile',
      payload: res.data,
    });
  };
};

export const updateProfileAction = (data: Partial<ProfileType>) => {
  return async (dispatch: AppDispatch) => {
    await updateProfileAPI(data);
    // 更新redux
    dispatch({
      type: 'user/updateProfile',
      payload: data,
    });
  };
};
